//
//  PictureViewController.m
//  BSLCar
//
//  Created by dlios on 15/6/1.
//  Copyright (c) 2015年 lyz. All rights reserved.
//

#import "PictureViewController.h"
#import "LCModel.h"
#import <UIImageView+WebCache.h>
#import "UMSocial.h"
#import <SDImageCache.h>

@interface PictureViewController () <UIScrollViewDelegate, UIGestureRecognizerDelegate>

{
    UIImageView *imageview;
    CGFloat centenPoint;
    int i;
}

@property (nonatomic, retain) UIScrollView *mScrollView;
@property (nonatomic, retain) UILabel *nameLabel;
@property (nonatomic, retain) UILabel *indexLabel;
@property (nonatomic, assign) NSInteger flag;

@end

@implementation PictureViewController

- (void)dealloc
{
    [_mScrollView release];
    [_nameLabel release];
    [_indexLabel release];
    [_dataArray release];
    [_serid release];
    [_typeId release];
    [super dealloc];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    
    i = 0;
    
    self.flag = self.index;

    self.view.backgroundColor = [UIColor blackColor];
    [self setNeedsStatusBarAppearanceUpdate];
    
    self.mScrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:self.mScrollView];
    self.mScrollView.tag = 1000;
    self.mScrollView.contentSize = CGSizeMake(self.view.bounds.size.width * self.piccount, 0);
    self.mScrollView.contentOffset = CGPointMake(self.view.bounds.size.width * self.index, 0);
    self.mScrollView.delegate = self;
    self.mScrollView.bouncesZoom = NO;
    self.mScrollView.bounces = NO;
    self.mScrollView.pagingEnabled = YES;
    [_mScrollView release];

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture)];
    [self.view addGestureRecognizer:tapGesture];
    [tapGesture release];

    [self.navigationController setNavigationBarHidden:YES];
    
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, self.view.bounds.size.width - 20, 20)];
    self.nameLabel.textAlignment = NSTextAlignmentCenter;
    self.nameLabel.textColor = [UIColor whiteColor];
    LCModel *md = [self.dataArray objectAtIndex:self.index];
    self.nameLabel.text = md.specname;
    [self.view addSubview:self.nameLabel];
    
    self.indexLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, self.view.bounds.size.height - 40, self.view.bounds.size.width - 200, 20)];
    self.indexLabel.textAlignment = NSTextAlignmentCenter;
    self.indexLabel.textColor = [UIColor whiteColor];
    self.indexLabel.text = [NSString stringWithFormat:@"%ld/%ld", self.index + 1, self.piccount];
    [self.view addSubview:self.indexLabel];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(20, self.view.bounds.size.height - 50, 30, 30);
    [button setImage:[UIImage imageNamed:@"iconfont-xz"] forState:UIControlStateNormal];
    [self.view addSubview:button];
    [button addTarget:self action:@selector(baocun:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button2.frame = CGRectMake(self.view.bounds.size.width - 60, self.view.bounds.size.height - 50,30, 30);
    [button2 setImage:[UIImage imageNamed:@"iconfont-fx"] forState:UIControlStateNormal];
    [self.view addSubview:button2];
    [button2 addTarget:self action:@selector(fenxiang) forControlEvents:UIControlEventTouchUpInside];
    
    [self scrollView];
}

- (void)fenxiang
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"556343f267e58ed117001f59"
                                      shareText:self.nameLabel.text
                                     shareImage:imageview.image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,nil]
                                       delegate:nil];
}


- (void)baocun:(UIButton *)sender {
    UIImageWriteToSavedPhotosAlbum(imageview.image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
}

- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (!error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存成功" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [alert show];
        [self.view addSubview:alert];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存失败" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [alert show];
        [self.view addSubview:alert];
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

- (NSMutableArray *)parserUrlRequest { //  cg 1 外观 10中控  3座椅  12其他
    NSMutableArray *rootarray = [NSMutableArray array];
    NSString *string = @"http://baojiac.qichecdn.com/v3.5.5/cars/pics-a2-pm2-v3.9.1-ss";
    string = [NSString stringWithFormat:@"%@%@-sp0-cg%@-cl0-p%ld-s60.html", string, self.serid, self.typeId, self.pageindex];
    NSURL *url = [NSURL URLWithString:string];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:20];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSDictionary *diction = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dict = [diction objectForKey:@"result"];
        NSArray *array = [dict objectForKey:@"piclist"];
        self.piccount = [[dict objectForKey:@"rowcount"] integerValue];
        for (NSDictionary *dic in array) {
            LCModel *model = [LCModel getLCModel];
            model.picurl = [dic objectForKey:@"smallpic"];
            model.specname = [dic objectForKey:@"specname"];
            [self.dataArray addObject:model];
            [rootarray addObject:model];
        }
    }];
    return rootarray;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ((self.index + 1) / 60 == self.pageindex && self.pageindex < self.pagecount) {
        self.pageindex++;
        [self parserUrlRequest];
    }
    self.index = self.mScrollView.contentOffset.x / self.view.bounds.size.width;
    self.indexLabel.text = [NSString stringWithFormat:@"%ld/%ld", self.index + 1, self.piccount];
    LCModel *md = [self.dataArray objectAtIndex:self.index];
    self.nameLabel.text = md.specname;

    if (self.index == i) {
        [self scrollView];
    }
}

- (void)scrollView {
    for (; i < self.index + 10 && i < self.piccount; i++) {
        UIScrollView *scrView = [[UIScrollView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width * i, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
        scrView.backgroundColor = [UIColor clearColor];
        scrView.delegate = self;

        scrView.minimumZoomScale = 1;
        scrView.maximumZoomScale = 13;
        UIImageView *imagevieww = [[UIImageView alloc] init];
        imagevieww.frame = CGRectMake(0, self.view.bounds.size.height / 2 - 200, self.view.bounds.size.width, 300);
        imagevieww.userInteractionEnabled = YES;

        LCModel *model = [self.dataArray objectAtIndex:i];
        [imagevieww sd_setImageWithURL:[NSURL URLWithString:model.picurl] placeholderImage:[UIImage imageNamed:@"Bei"]];
        imagevieww.contentMode = UIViewContentModeScaleAspectFit;
        [scrView addSubview:imagevieww];
        [self.mScrollView addSubview:scrView];
        [scrView release];
    }
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
    (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
    (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    
    imageview.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX, scrollView.contentSize.height * 0.5 + offsetY);
}

-  (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.tag == 1000) {
        for (UIScrollView *view in scrollView.subviews) {
            if (view.tag == self.index ) {
                imageview = (UIImageView *)[view.subviews firstObject];
            }

        }
        if (self.flag != self.index) {
            UIScrollView *scrollView = [self.mScrollView.subviews objectAtIndex:self.flag];
            scrollView.zoomScale = 1.f;
            self.flag = self.index;
        }
    }
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    if (scrollView.tag != 1000) {
        return scrollView.subviews.firstObject;
    }
    return nil;
}

- (void)tapGesture {
    [self.navigationController popViewControllerAnimated:YES];
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
